package com.niit.chat.mapper;

import com.niit.chat.vo.MessageSessionVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
import java.util.Map;

/**
 * 消息会话Mapper接口
 */
@Mapper
public interface MessageSessionMapper {
    
    /**
     * 获取用户的所有会话列表
     * @param userId 用户ID
     * @return 会话列表
     */
    @Select("SELECT " +
            "m.id AS id, " +
            "CASE WHEN m.sender_id = #{userId} THEN m.receiver_id ELSE m.sender_id END AS friendId, " +
            "u.nickname AS nickName, " +
            "u.avatar AS avatar, " +
            "m.content AS lastMessage, " +
            "m.update_date AS lastMessageTime " +
            "FROM ( " +
            "    SELECT LEAST(sender_id, receiver_id) AS min_id, GREATEST(sender_id, receiver_id) AS max_id, MAX(id) AS message_id " +
            "    FROM tb_message " +
            "    WHERE sender_id = #{userId} OR receiver_id = #{userId} " +
            "    GROUP BY LEAST(sender_id, receiver_id), GREATEST(sender_id, receiver_id) " +
            ") AS latest " +
            "JOIN tb_message m ON m.id = latest.message_id " +
            "JOIN tb_user u ON u.id = CASE WHEN m.sender_id = #{userId} THEN m.receiver_id ELSE m.sender_id END " +
            "ORDER BY m.update_date DESC")
    List<MessageSessionVO> getUserSessions(@Param("userId") Long userId);
    
    /**
     * 获取两个用户之间的会话
     * @param userId 当前用户ID
     * @param friendId 好友用户ID
     * @return 会话信息
     */
    @Select("SELECT " +
            "m.id AS session_id, " +
            "u.id AS friend_id, " +
            "u.nickname AS friend_nickname, " +
            "u.avatar AS friend_avatar, " +
            "m.content AS last_message, " +
            "m.update_date AS last_message_time " +
            "FROM tb_message m " +
            "JOIN tb_user u ON u.id = #{friendId} " +
            "WHERE (m.sender_id = #{userId} AND m.receiver_id = #{friendId}) " +
            "   OR (m.sender_id = #{friendId} AND m.receiver_id = #{userId}) " +
            "ORDER BY m.update_date DESC " +
            "LIMIT 1")
    MessageSessionVO getSession(@Param("userId") Long userId, @Param("friendId") Long friendId);
    
    /**
     * 获取用户信息
     * @param userId 用户ID
     * @return 用户信息
     */
    @Select("SELECT id, nickname, avatar " +
            "FROM tb_user " +
            "WHERE id = #{userId}")
    Map<String, Object> getUserInfo(@Param("userId") Long userId);
    
    /**
     * 删除会话（逻辑删除）
     * @param sessionId 会话ID
     * @param userId 用户ID
     * @return 影响的行数
     */
    @Update("UPDATE tb_message " +
            "SET is_deleted = 1 " +
            "WHERE id <= #{sessionId} AND (sender_id = #{userId} OR receiver_id = #{userId})")
    int deleteSession(@Param("sessionId") Long sessionId, @Param("userId") Long userId);
}